package com.centsuse.my_redis.controller;

import com.centsuse.my_redis.dao.CallerToken;
import com.centsuse.my_redis.service.CallerTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 业务方Token管理接口
 */
@RestController
@RequestMapping("/api/caller-tokens")
public class CallerTokenController {

    @Autowired
    private CallerTokenService callerTokenService;

    /**
     * 根据caller标识获取Token信息
     */
    @GetMapping("/{caller}")
    public ResponseEntity<CallerToken> getCallerToken(
            @PathVariable String caller) {
        CallerToken callerToken = callerTokenService.getCallerToken(caller);
        return callerToken != null ?
                ResponseEntity.ok(callerToken) :
                ResponseEntity.notFound().build();
    }

    /**
     * 根据caller标识获取Token信息
     */
    @GetMapping("getByCache/{caller}")
    public ResponseEntity<CallerToken> getCallerTokenByCache(
            @PathVariable String caller) {
        CallerToken callerToken = callerTokenService.getCallerTokenByCache(caller);
        return callerToken != null ?
                ResponseEntity.ok(callerToken) :
                ResponseEntity.notFound().build();
    }

    /**
     * 创建新的业务方Token
     */
    @PostMapping
    public ResponseEntity<CallerToken> createCallerToken(
            @RequestBody CallerToken callerToken) {
        CallerToken createdToken = callerTokenService.insertCallerToken(callerToken);
        return createdToken != null ?
                ResponseEntity.ok(createdToken) :
                ResponseEntity.badRequest().build();
    }

    /**
     * 更新业务方Token信息
     */
    @PutMapping("/{caller}")
    public ResponseEntity<CallerToken> updateCallerToken(
            @PathVariable String caller,
            @RequestBody CallerToken callerToken) {
        // 确保路径参数与请求体中的caller一致
        if (!caller.equals(callerToken.getCaller())) {
            return ResponseEntity.badRequest().build();
        }

        // 先检查是否存在
        CallerToken existing = callerTokenService.getCallerToken(caller);
        if (existing == null) {
            return ResponseEntity.notFound().build();
        }

        CallerToken updatedToken = callerTokenService.insertCallerToken(callerToken);
        return updatedToken != null ?
                ResponseEntity.ok(updatedToken) :
                ResponseEntity.badRequest().build();
    }
}